package com.junsi.app.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.junsi.app.common.exception.UnauthorizedException;
import com.junsi.app.common.page.ResultData;
import com.junsi.app.common.util.JwtUtil;
import com.junsi.common.utils.StringUtils;
import com.junsi.common.utils.http.HttpUtils;
import com.junsi.common.utils.security.Md5Utils;
import com.junsi.system.domain.SysUser;
import com.junsi.system.service.ISysUserService;
import com.junsi.system.vo.SSoUserInfo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@Api(tags = "登录相关")
@RestController
public class WebController
{

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * 获取用户信息接口
	 */
	@Value("${sso.user.client_url}")
	private String userInfoUrl;

	@Value("${sso.user.client_id}")
	private String clientId;

	@Autowired
	private ISysUserService sysUserService;

	@ApiOperation("登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username",required=true,paramType="form", value = "用户名", dataType = "String"),
			@ApiImplicitParam(name = "password",required=true,paramType="form", value = "密码", dataType = "String")
	})
	@PostMapping("/login")
	public ResultData login(@RequestParam("username") String username, @RequestParam("password") String password)
	{
		SysUser user = sysUserService.selectUserByLoginName(username);
		if(null == user){
			throw new UnauthorizedException("用户不存在");
		}
		if(StringUtils.isEmpty(user.getPassword())){
			throw new UnauthorizedException("请先初始化密码");
		}
		if (user.getPassword().equals(Md5Utils.encryptPassword(user.getLoginName(), password, user.getSalt())))
		{
			return ResultData.success(JwtUtil.sign(user.getLoginName(), null));
		}
		else
		{
			throw new UnauthorizedException();
		}
	}

	@ApiOperation("article")
	@GetMapping("/article")
	public ResultData article()
	{
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated())
		{
			return ResultData.successMsg("You are already logged in");
		}
		else
		{
			return ResultData.successMsg("You are guest");
		}
	}

	@GetMapping("/require_auth")
	@RequiresAuthentication
	public ResultData requireAuth()
	{
		return ResultData.successMsg("You are authenticated");
	}

	@GetMapping("/require_role")
	@RequiresRoles("admin")
	public ResultData requireRole()
	{
		return ResultData.successMsg("You are visiting require_role");
	}

	@GetMapping("/require_permission")
	@RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})
	public ResultData requirePermission()
	{
		return ResultData.successMsg("You are visiting permission require edit,view");
	}

	@RequestMapping(path = "/401/{message}")
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ResultData unauthorized(@PathVariable(value = "message") String message)
	{
		return ResultData.error(401, message);
	}

//	@ApiOperation("获取tokenTest")
//	@PostMapping("/bt/getTokenTest")
//	public ResultData getTokenTest(HttpServletRequest request, HttpServletResponse response)
//	{
//		String t = JwtUtil.sign("admin", null);
//		logger.info("token:------------> "+t);
//		return ResultData.success(t);
//	}

	/**
	 * 调用获取授权接口 单点登录成功跳转
	 * @param request
	 * @param response
	 * @return
	 */
	@ApiOperation("获取token")
	@PostMapping("/bt/getToken")
	public ResultData getToken(HttpServletRequest request, HttpServletResponse response)
	{

		String token =  request.getParameter("token");
		logger.info("token:------------> "+token);
		if(!StringUtils.isBlank(token)) {
			/**
			 * 请求模式为 GET
			 * 接口： https://loginuat.countrygarden.com.cn:8443/idp/oauth2/getUserInfo
			 * client_id=bip（由认证平台提供和上一个接口中为相同参数）
			 * access_token：由上一步获取 access_token 值
			 */
			Map<String, Object> userRMap = new HashMap<String, Object>();
			userRMap.put("client_id", clientId);
			userRMap.put("access_token", token);
			String userInofResult = HttpUtils.sendGet(userInfoUrl, userRMap);
			if (StringUtils.isEmpty(userInofResult.trim())) {
				return ResultData.error(0, "sso return empty");
			}

			SSoUserInfo sSoUserInfo = JSON.parseObject(userInofResult, SSoUserInfo.class);
			if(sSoUserInfo==null || CollectionUtils.isEmpty(sSoUserInfo.getSpRoleList()) || sSoUserInfo.getSpRoleList().get(0)==null) {
				return ResultData.error(0, "get access token empty");
			}

			// TODO: 2019/5/22 测试写死
			if ("wangxiongpo".equals(sSoUserInfo.getSpRoleList().get(0).toString())) {
				System.out.println("wangxiongpo login success");
				String st = JwtUtil.sign("admin", null);
//				System.out.println("token -------->" + st);
				logger.info("token:------------> "+st);
				return ResultData.success(st);
			} else {
				// 查询用户信息
				SysUser user = sysUserService.selectUserByLoginName(sSoUserInfo.getSpRoleList().get(0).toString());
				if (user == null) {
					ResultData.error(0, "user not exists");
				}
//				System.out.println("login other");
				String st = JwtUtil.sign(user.getLoginName(), null);
//				System.out.println("token -------->" + st);
				logger.info("token:------------> "+st);
				return ResultData.success(st);
			}
		}

//			String[] s = token.split(",");
//			logger.info(s[0]);
//			logger.info(s[1]);
//			String device =s[1];
//			String encryptedString = s[0];
//
//			Map tmap = new HashMap();
//			tmap.put("device",device);
//			tmap.put("encryptedString",encryptedString);
//
//			Map<String, String> headers = new HashMap();
//			headers.put("operator","ybapp");
//			headers.put("Content-Type","application/json");
//
//			String result = null;
//			try {
//				result = HttpClientUtils.post(headers,userInfoUrl,JSONUtils.toJSONString(tmap),"application/json", "UTF-8", 10000, 10000);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
//			System.out.println("result------->"+result);
//			if(StringUtils.isEmpty(result.trim())){
//				ResultData.eoror(10001,"sso return empty");
//			}
//			Map map = (Map) JSONUtils.parse(result);
//			ResultData resultData = new ResultData();
//			if(StringUtils.isNotEmpty(map.get("status").toString())){
//				if(!"success".equals(map.get("status").toString())){
//					resultData.setCode(10003);
//					resultData.setMsg(map.get("message").toString());
//					return resultData;
//				}
//			}
//
//			System.out.println("body-------->"+map.get("body").toString());
//			Map map2 = (Map)JSONUtils.parse(JSONUtils.toJSONString(map.get("body")));
//			System.out.println("username------->"+map2.get("username").toString());
//
//
//			// TODO: 2019/5/22 测试写死
//			if("wangxiongpo".equals(map2.get("username").toString())){
//				System.out.println("wangxiongpo login success");
//				String st =JwtUtil.sign("admin", null);
//				System.out.println("token -------->"+ st);
//				return ResultData.success(st);
//			}else {
//				// 查询用户信息
//				SysUser user = sysUserService.selectUserByLoginName(map2.get("username").toString());
//				if(user == null){
//					ResultData.eoror(10004,"user not exists");
//				}
//				System.out.println("login other");
//				String st =JwtUtil.sign(user.getLoginName(), null);
//				System.out.println("token -------->"+ st);
//				return ResultData.success(st);
//			}
//		}
		return ResultData.error(10002,"token is null");
	}

}